/**
 * 功能描述
 */

define(function (require, exports, module) {
	var aw = require("ajaxwrapper");
	var Dialog = require("dialog");
	
	var fetchProperties = require("../constant/fetchProperties");
	var processData = require("../store/processData");
	var preAdjustSubGrid = require("../component/preAdjustSubGrid");
	var preAdjustTab=require("../component/preAdjustTab");
	var preAdjustRoomGrid=require("../component/preAdjustRoomGrid");
	
    module.exports = {
		adjustmentEvent:function(widget,data){
			widget.set("deleteRoom",false);
			widget.set("data",data);
			// 体验之外的散客走另外的调整流程
        	if(data.nonMemberGroup && data.nonMemberGroup.signUpType.key == "NonMember"){
        		widget.NonMember = true;
        		widget.signUpRoomDatas = [];
        	}else{
        		widget.NonMember = false;
        	}
			widget.toForm(data);
			widget.set("subGrid","");
			widget.adjustTypes = [];
			widget.exitData=[];
	        widget.signUpDatas=[];
			$("#J-subGrid").empty();
			$(".J-tab").empty();
			$("#applyAdd").show();
			$("#roomAdd").show();
			$(".J-grid-roomGrid-del").show();
			$(".J-tab").show();
			var adjsutForm = widget.get('adjsutForm');
			adjsutForm.reset();
			adjsutForm.setValue("dataSource",data.dataSource.key);
			if(widget.NonMember){//散客
				adjsutForm.setValue("pkGroup",data.nonMemberGroup.pkNonMemberGroup);
				adjsutForm.setValue("version",data.nonMemberGroup.version);
				// 预约散客调整流程区别于其他的
				var form = widget.get("form");
				form.reset();
				form.setData(data.nonMemberGroup);
				form.setValue("signUpType", data.nonMemberGroup.signUpType.key);
				form.setValue("status", data.nonMemberGroup.status.key);
				form.setValue("operator", data.nonMemberGroup.operator.pkUser);
				if(data.nonMemberGroup.chargeDeposit){
					form.setValue("chargeDeposit","true");
				}else{
					form.setValue("chargeDeposit","false");
				}
				form.setDisabled(true);
				aw.ajax({
					url: "api/nonmemgroupreserve/query",
					data: {
						"nonMemberGroup": data.nonMemberGroup.pkNonMemberGroup,
						fetchProperties: fetchProperties.querySignUpRooms
					},
					dataType: "json",
					success: function(datas){
						widget.signUpRoomDatas = $.extend(true,[], datas[0].signUpRooms);
						if(!widget.get("check")){
							form.setDisabled("checkInDate", false);
							form.setDisabled("checkOutDate", false);
							form.setDisabled("perNumber", false);
							widget.get("editgrid").setData(datas[0].signUpRooms);
							$("#editgrid").show();
							$("#reserveRoomDetailGrid").hide();
						}else{
							$("#reserveRoomDetailGrid").show();
							widget.get("reserveRoomDetailGrid").setData(datas[0].signUpRooms);
							$("#editgrid").hide();
						}
						return;
					}
				})
			}
			if(data.planItemGroup){//组团
				var groupReserve;
				if(data.planItemGroup.allianceOrg){
					groupReserve = data.planItemGroup.allianceOrg.name;
				}else{
					groupReserve = data.planItemGroup.servicePoint.name
				}
				adjsutForm.setValue("destination",data.planItemGroup.planItem.destination.name);
				adjsutForm.setValue("checkInDate",data.planItemGroup.planItem.startDate);
				adjsutForm.setValue("checkOutDate",data.planItemGroup.planItem.endDate);
				adjsutForm.setValue("groupReserve",groupReserve);
				adjsutForm.setValue("pkGroup",data.planItemGroup.pkPlanItemGroup);
				adjsutForm.setValue("version",data.planItemGroup.version);
				
				var gridData = data.planItemGroup.signUps;
				if(data.planItemGroup.alliance){//联盟入住直属 联盟入住联盟 
					preAdjustTab.renderTab(widget);
					preAdjustRoomGrid.renderGrid(widget);
					preAdjustSubGrid.renderGrid(widget,false,false);
					var roomGrid=widget.get("roomGrid");
					var subGrid = widget.get("subGrid"),
						subGridData = [];
					for(var i=0;i<gridData.length;i++){
						if(!gridData[i].exitGroup){
							subGridData.push(gridData[i])
						}else{
							widget.exitData.push(gridData[i]);
						}
					}
					adjsutForm.setValue("signUpNum",subGridData.length);
					subGrid.setData(subGridData);
					roomGrid.setData(data.groupReserve?data.groupReserve.roomRegisters:null);
					widget.signUpDatas = gridData;
					widget.showRoomBtn(data);
					if(widget.get("check")||data.groupType.key=="AllianceToAlliance"){
						$("#roomAdd").hide();
						$(".J-grid-roomGrid-del").hide();
					}else{
						$("#roomAdd").show();
						$(".J-grid-roomGrid-del").show();
					}
				}else{//直属 直属入住直属
					widget.service.queryChargeStatus({
						"pkPlanItemGroup":data.planItemGroup.pkPlanItemGroup,
						fetchProperties:fetchProperties.chargestatus
					},function(data){
						var gridData = processData.processCharge(widget,data);
						preAdjustTab.renderTab(widget);
						preAdjustRoomGrid.renderGrid(widget);
						preAdjustSubGrid.renderGrid(widget,true,false);
						var roomGrid=widget.get("roomGrid");
						var subGrid = widget.get("subGrid"),
							subGridData = [];
						for(var i=0;i<gridData.length;i++){
							if(!gridData[i].exitGroup){
								subGridData.push(gridData[i])
							}
//							else{
//								widget.exitData.push(gridData[i]);
//							}
						}
						adjsutForm.setValue("signUpNum",subGridData.length);
						subGrid.setData(gridData);
						roomGrid.setData(data.length>0?data[0].groupReserve?data[0].groupReserve.roomRegisters:[]:[]);
						widget.signUpDatas = gridData;
						
						if(data.length>0&&data[0].groupReserve&&data[0].groupReserve.checkInType.key=="Alliance"){//联盟机构
							$("#roomAdd").hide();
							$(".J-grid-roomGrid-del").hide();
						}else if(widget.get("check")){//如果点击查看按钮，隐藏增加人员按钮和退团按钮
							$("#applyAdd").hide();
							$("#roomAdd").hide();
							$(".J-grid-roomGrid-del").hide();
							$(".J-grid-subGrid-exit").hide();
						}else if(data.length>0&&data[0].signUpRegister&&data[0].signUpRegister.planItemGroup.checkInStatus.key=="Reserve"){//已预约
							$("#roomAdd").show();
							$(".J-grid-roomGrid-del").show();
						}else{
							$("#roomAdd").hide();
							$(".J-grid-roomGrid-del").hide();
						}
					})
				}
			}else{
				preAdjustTab.renderTab(widget);
				preAdjustRoomGrid.renderGrid(widget);
				preAdjustSubGrid.renderGrid(widget,true,false);
				$("#roomAdd").hide();
				$(".J-grid-roomGrid-del").hide();
				var signUpType = data.nonMemberGroup.signUpType.key,
					tourType = data.nonMemberGroup.tourType,
					groupReserve,
					IndivMember = false;
				if(signUpType == "NonMember"){
					groupReserve = data.nonMemberGroup.groupUnit;
				}else{
					groupReserve = data.nonMemberGroup.operator.servicePoint.name;
				}
				if(tourType && tourType.key == "IndivMember"){
					IndivMember = true;
				}
				adjsutForm.setValue("destination",data.nonMemberGroup.servicePoint.name);
				adjsutForm.setValue("checkInDate",data.nonMemberGroup.checkInDate);
				adjsutForm.setValue("checkOutDate",data.nonMemberGroup.checkOutDate);
				adjsutForm.setValue("groupReserve",groupReserve);
				adjsutForm.setValue("pkGroup",data.nonMemberGroup.pkNonMemberGroup);
				adjsutForm.setValue("version",data.nonMemberGroup.version);
				
				var signUps = data.nonMemberGroup.signUps,
					gridData = [];
				
				for(var i=0;i<signUps.length;i++){
					gridData.push(signUps[i].signUpRegister);
				}
				var subGrid = widget.get("subGrid"),
					subGridData = [];
				for(var i=0;i<gridData.length;i++){
					if(!gridData[i].exitGroup){
						subGridData.push(gridData[i])
					}else{
						widget.exitData.push(gridData[i]);
					}
				}
				adjsutForm.setValue("signUpNum",subGridData.length);
				subGrid.setData(subGridData);
				widget.signUpDatas = gridData;
			}
		},
		applyAddEvent:function(widget){
			widget.toAddForm();
			var adjsutForm = widget.get("adjsutForm"),
			pkGroup = adjsutForm.getValue("pkGroup"),
			dataSource = adjsutForm.getValue("dataSource"),
			cData = widget.get("tempGridRowData"),
			addForm = widget.get("addForm");
		
			addForm.setValue("dataSource",dataSource);
			addForm.setValue("pkGroup",pkGroup);
			if(cData.planItemGroup){
				if(cData.planItemGroup.alliance){
					addForm.show("personalInfo.idNumber").hide(["idNumberSearch", "travelContractObj", "memberObj"]);
				}else{
					addForm.show(["travelContractObj","personalInfo.name","personalInfo.idNumber"]).hide(["idNumberSearch", "memberObj"]);
				}
			}else{
				if(cData.nonMemberGroup.signUpType.key == "NonMember"){
					if(cData.nonMemberGroup.tourType.key == "IndivMember"){
						addForm.show(["memberObj", "personalInfo.idNumber", "travelContractObj"]).hide(["idNumberSearch", "personalInfo.name"]);
					}else{
						addForm.show("personalInfo.idNumber").hide(["idNumberSearch", "travelContractObj", "memberObj"]);
					}
				}else{
					addForm.show(["idNumberSearch", "personalInfo.name"]).hide(["travelContractObj", "personalInfo.idNumber", "memberObj"]);
				}
			}
		},
		addRoomEvent:function(widget){
			var data=widget.get("data");
			widget.toAddRoomForm();
			addRoomForm = widget.get("addRoomForm");
			addRoomForm.setValue("pkGroupReserve",data.groupReserve!=null?data.groupReserve.pkGroupReserve:null);
			addRoomForm.setValue("version",data.groupReserve!=null?data.groupReserve.version:null);
			addRoomForm.load("orgBuilding",{
	          	callback: function(data){
	          	}
	         });
		},
		changeFormBuild:function(widget){
			var addRoomForm=widget.get("addRoomForm");
			addRoomForm.setData("room",[]);
			addRoomForm.load("roomType",{
                params : {
                	orgBuilding: addRoomForm.getValue("orgBuilding"),
                	fetchProperties:"pkRoomType,name"
				},
      			callback: function(ret){
      			}
      		});
		},
		changeFormRoom:function(widget){
			var addRoomForm=widget.get("addRoomForm");
			var adjsutForm = widget.get("adjsutForm");
			widget.get("addRoomForm").load("room",{
                params : {
            		orgBuilding:addRoomForm.getValue("orgBuilding"),
					roomType:addRoomForm.getValue("roomType"),
					startDate: adjsutForm.getValue("checkInDate"),
					endDate: adjsutForm.getValue("checkOutDate"),
					status:"Clear",
					fetchProperties:"room.pkRoom,room.code,room.status,room.version"
				},
      			callback: function(ret){
      				var rooms=[];
      				for(var i=0;i<ret.length;i++){
      					rooms.push(ret[i].room);
      				}
      				widget.get("addRoomForm").setData("room",rooms);
      			}
      		});
		},
		addSaveEvent:function(widget){
			var addForm = widget.get("addForm"),
				adjsutForm = widget.get("adjsutForm"),
				subGrid = widget.get("subGrid"),
				subGridData = subGrid.getData(),
				addData = addForm.getData(),
				isMember = addData.member == "true" ? true:false,
				isCustomer = addData.customer == "true" ? true:false;
    		
			var signUpRegister = {};
    		if(!isMember && !isCustomer){	// 不是会员
    			signUpRegister = {
    				member:isMember,
    				customer:isCustomer,
    				pkSignUpRegister:addData.pkSignUpRegister,
    				version:addData.version,
    				personalInfo :{
    					name:addData["personalInfo.name"],
    					mobilePhone:addData["personalInfo.mobilePhone"],
    					idNumber:addData["personalInfo.idNumber"] == "" ? $("input[name='idNumberSearch']").val() : addData["personalInfo.idNumber"],
    					sex:addData["personalInfo.sex"],
    					version:addData["personalInfo.version"]
    				},
    				travelContract:{
    					memberCertificates:addData["memberCertificates"],
    					pkTravelContract:addData["pkTravelContract"],
    					member:{
    						personalInfo:{
    							idNumber:addData["travelContract.member.personalInfo.idNumber"],
    							name: addData["travelContract.member.personalInfo.name"]
    						}
    					},
    					productRule:{
    						product:{
    							name:addData["productName"]
    						}
    					}
    				},
    				contactName : addData.contactName,
    				contactPhone : addData.contactPhone,
    				exitGroup : false
    			};    			
    		}else{
    			signUpRegister = {
    				pkSignUpRegister:addData.pkSignUpRegister,
    				version:addData.version,
    				member:isMember,
    				customer:isCustomer,
    				contactName : addData.contactName,
    				contactPhone : addData.contactPhone,
    				personalInfo :{
    					name:addData["personalInfo.name"],
    					mobilePhone:addData["personalInfo.mobilePhone"],
    					idNumber:addData["personalInfo.idNumber"] == "" ? $("input[name='idNumberSearch']").val() : addData["personalInfo.idNumber"],
    					sex:addData["personalInfo.sex"],
    					version:addData["personalInfo.version"],
    					pkPersonalInfo:addData["personalInfo.pkPersonalInfo"],
    				},
    				travelContract:{
    					memberCertificates:addData["memberCertificates"],
    					pkTravelContract:addData["pkTravelContract"],
    					member:{
    						personalInfo:{
    							idNumber:addData["travelContract.member.personalInfo.idNumber"],
    							name: addData["travelContract.member.personalInfo.name"]
    						}
    					},
    					productRule:{
    						product:{
    							name:addData["productName"]
    						}
    					}
    				},
    				exitGroup : false
    			};	
    		}
    		subGridData.push(signUpRegister);
    		subGrid.setData(subGridData);
    		
    		var data = widget.get("tempGridRowData");
        	widget.toForm(data);
		},
		saveEvent:function(widget){
			var subGrid = widget.get("subGrid"),
				subGridData = subGrid.getData(),
				adjsutForm = widget.get("adjsutForm"),
				formData = adjsutForm.getData(),
				temp = [],
				rooms=[];
			if(subGridData.length == 0){
				Dialog.alert({
					tip : "提示",
					content : "报名人员不能为空！"
				})
				return false;
			}
			
			// 判断调整类型
			var preDate,perEndDate;
			var affectRoomType = false;
			var groupType = widget.get("tempGridRowData").groupType.key;	// 团类型
			var groupStatus = widget.get("tempGridRowData").groupStatus.key;	// 团状态
			if(adjsutForm.getValue("dataSource") == "NonMember"){
				preDate = widget.get("tempGridRowData").nonMemberGroup.checkInDate;
				perEndDate = widget.get("tempGridRowData").nonMemberGroup.checkOutDate;
			}else{
				preDate = widget.get("tempGridRowData").planItemGroup.planItem.startDate;
				perEndDate = widget.get("tempGridRowData").planItemGroup.planItem.endDate;
			};
			var flag = false; // 日期调整
			var adjustDate = adjsutForm.getValue("checkInDate");
			var adjustEndDate = adjsutForm.getValue("checkOutDate");
			if(preDate > adjustDate){	// 提前-根据开始日期判断
				widget.adjustTypes.push("Advanced");
				// 预约阶段的直属入住直属，联盟入住直属，散客团才影响预约房间、房型
				if(groupStatus == "Reserve" && (groupType == "OrgToOrg"
					|| groupType == "AllianceToOrg"
						|| adjsutForm.getValue("dataSource") == "NonMember")){
					flag = true;
				}
			}
			if(preDate < adjustDate){	// 推迟-根据开始日期判断
				widget.adjustTypes.push("Delayed");
				// 预约阶段的直属入住直属，联盟入住直属，散客团才影响预约房间、房型
				if(groupStatus == "Reserve" && (groupType == "OrgToOrg"
					|| groupType == "AllianceToOrg"
						|| adjsutForm.getValue("dataSource") == "NonMember")){
					flag = true;
				}
			}
			if(adjustEndDate > perEndDate){
				if(preDate == adjustDate){	// 提前-开始日期未变，则根据结束日期判断
					widget.adjustTypes.push("Delayed");
				}
				// 预约阶段的直属入住直属，联盟入住直属，散客团才影响预约房间、房型
				if(groupStatus == "Reserve" && (groupType == "OrgToOrg"
					|| groupType == "AllianceToOrg"
						|| adjsutForm.getValue("dataSource") == "NonMember")){
					flag = true;
				}
			}
			if(preDate == adjustDate && adjustEndDate < perEndDate){	// 推迟-开始日期未变，则根据结束日期判断
				widget.adjustTypes.push("Advanced");
			}
			for(var i = 0; i < subGridData.length; i++){
				if(subGridData[i].pkSignUpRegister == null 
						|| subGridData[i].pkSignUpRegister == ""){
					widget.adjustTypes.push("Turnover");
					break;
				}
			}
			rooms=widget.get("roomGrid").getData();
			var roomsData=[];
			if(widget.get("deleteRoom")){//删除房间
				widget.adjustTypes.push("Room");
			}
			for(var i=0;i<rooms.length;i++){//未删除房间
				if(!widget.get("deleteRoom")&&(rooms[i].pkSignUpRegister == null 
						|| rooms[i].pkSignUpRegister == "")){
					widget.adjustTypes.push("Room");
					break;
				}
			}
			for(var i=0;i<rooms.length;i++){
				if(rooms[i].room.status&&typeof rooms[i].room.status != "string"){
					rooms[i].room.status = rooms[i].room.status.key;
				}
				if(rooms[i].status){
					rooms[i].status = null;
				}
			}
			if(widget.exitData){
				temp = subGridData.concat(widget.exitData);  
			}
			for(var i = 0; i < temp.length; i++){
				if(typeof temp[i].personalInfo != "string" && temp[i].personalInfo.pkPersonalInfo){
					temp[i].personalInfo = temp[i].personalInfo.pkPersonalInfo;
				}
				if(temp[i].travelContract && typeof temp[i].travelContract !="string"){
					temp[i].travelContract = temp[i].travelContract.pkTravelContract;
				}
				if(temp[i].personalInfo.sex  && (typeof temp[i].personalInfo.sex != "string")){
					temp[i].personalInfo.sex = temp[i].personalInfo.sex.key;
				}
				if(temp[i].personalInfo.idType && (typeof temp[i].personalInfo.idType != "string")){
					temp[i].personalInfo.idType = temp[i].personalInfo.idType.key;
				}
				if(temp[i].planItemGroup&&temp[i].planItemGroup.checkInStatus && (typeof temp[i].planItemGroup.checkInStatus != "string")){
					temp[i].planItemGroup.checkInStatus = temp[i].planItemGroup.checkInStatus.key;
				}
			}
			var obj = {};
			if(formData.dataSource == "NonMember"){
				var nonMemberGroup = {}
				nonMemberGroup = {
					pkNonMemberGroup:adjsutForm.getValue("pkGroup"),
					checkInDate:adjsutForm.getValue("checkInDate"),
					checkOutDate:adjsutForm.getValue("checkOutDate"),
					adjustTypes:widget.adjustTypes
				};
				obj["nonMemberGroup"] = nonMemberGroup;
			}else{
				var planItemGroup = {}
				planItemGroup = {
					pkPlanItemGroup:adjsutForm.getValue("pkGroup"),
					planItem:{
						startDate:adjsutForm.getValue("checkInDate"),
						endDate:adjsutForm.getValue("checkOutDate")
					},
					adjustTypes:widget.adjustTypes
				};
				obj["planItemGroup"] = planItemGroup;
			}
			if(flag){	//调整后日期影响了预约房型
				// 预约状态的（直属入住直属、联盟入住直属）
				if(groupType == "OrgToOrg" || groupType == "AllianceToOrg"){
					affectRoomType = true;
					Dialog.confirm({
						tip: "提示",
						content: "该团已经预约，日期调整后，请重新预约房号！",
						confirm: function(){
							obj["roomRegisterList"]=rooms;
							obj["signUpList"] = temp;
							obj["dataSource"] = adjsutForm.getValue("dataSource");
							obj["affectRoomType"] = affectRoomType;
							widget.service.allSaveSvc(aw.customParam(obj),function(ret){
								widget.toGrid();
								widget.get("grid").refresh();
							})
						}
					})
				}
				// 预约状态的（散客团）
				if(adjsutForm.getValue("dataSource") == "NonMember"){
					affectRoomType = true;
					obj["roomRegisterList"]=rooms;
					obj["signUpList"] = temp;
					obj["dataSource"] = adjsutForm.getValue("dataSource");
					obj["affectRoomType"] = affectRoomType;
					widget.service.allSaveSvc(aw.customParam(obj),function(ret){
						widget.toGrid();
						widget.get("grid").refresh();
					})
				}
			}else{
				obj["roomRegisterList"]=rooms;
				obj["signUpList"] = temp;
				obj["dataSource"] = adjsutForm.getValue("dataSource");
				obj["affectRoomType"] = affectRoomType;
				widget.service.allSaveSvc(aw.customParam(obj),function(ret){
					widget.toGrid();
					widget.get("grid").refresh();
				})
			}
		},
		saveRoomEvent:function(widget){
			var addRoomForm=widget.get("addRoomForm");
			var pkRoom=addRoomForm.getValue("room");
			var roomData=addRoomForm.getData("room");
			var data={};
			var room;
			for(var i=0;i<roomData.length;i++){
				if(roomData[i].pkRoom==pkRoom){
					room=roomData[i];
					data["room"]=room;
					data["status"]={"key":"Appoint","value":"预定房"};
					break;
				}
			}
			var pkBuild=addRoomForm.getValue("orgBuilding");
			var buildData=addRoomForm.getData("orgBuilding");
			var orgBuilding;
			for(var i=0;i<buildData.length;i++){
				if(buildData[i].pkOrgBuilding==pkBuild){
					orgBuilding=buildData[i];
					data["orgBuilding"]=orgBuilding;
					break;
				}
			}
			var pkRoomType=addRoomForm.getValue("roomType");
			var roomTypeData=addRoomForm.getData("roomType");
			var roomType;
			for(var i=0;i<roomTypeData.length;i++){
				if(roomTypeData[i].pkRoomType==pkRoomType){
					roomType=roomTypeData[i];
					data["roomType"]=roomType;
					break;
				}
			}
			var roomGrid=widget.get("roomGrid");
			var gridData=roomGrid.getData();
			gridData.push(data);
			roomGrid.setData(gridData);
//			widget.service.addRoom(aw.customParam(addRoomForm.getData()),function(ret){
//				widget.refreshRoomGrid(widget);
				widget.toRoomForm(widget.get("tempGridRowData"));
//			})
		}
    };
});